package edu.hubu.talentmanagementsystem.auth;

import edu.hubu.talentmanagementsystem.common.RedisUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author moonlan
 * date 2021/2/9 下午1:10
 */
@SuppressWarnings(value = "unused")
@Component
public class JwtTokenAuthenticationProvider implements AuthenticationProvider {

    private final RedisUtils redisUtils;

    public JwtTokenAuthenticationProvider(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = (String) authentication.getPrincipal();
        if (redisUtils.isTokenEnable(token)) {
            Payload payload = JwtUtils.getPayload(token);
            return new JwtToken(token, payload.getAuthorities());
        }
        throw new BadCredentialsException("认证失败");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtToken.class.isAssignableFrom(authentication);
    }
}
